'use strict'
const path = require('path');
const Koa = require('koa');
const static_server = require('koa-static');
const http = require('http');
const socketIO = require('socket.io');



const hostname = '127.0.0.1';
const port = 3000
const publicPath = path.join(__dirname, 'public');

// 创建koa实例
const app = new Koa(); //充当 http server

// 创建http server实例
const server = http.createServer(app.callback());

// 创建socket.io实例
const io = socketIO(server);

// 静态资源路由
app.use(static_server(publicPath));

// 存储所有在线用户
const users = new Map();



// 登录认证
io.use((socket, next) => {
    const { name, password } = socket.handshake.query;
    console.log('username:', name);
    console.log('password:', password);
    next();
});


// 存储历史消息
const history = [];


// 客户端连入

io.on('connection', (socket) => {
    const name = socket.handshake.query.name;
    const password = socket.handshake.query.password;


    console.log(`${name} connected`);

    if (password !== '123') {
        console.log('password is incorrect');
        socket.disconnect();
        return;
    }
    console.log('login successfully');
    users.set(name, socket);



    // 通知所有客户端更新聊天列表
    io.sockets.emit('online', [...users.keys()]);

    //监听客户端消息
    socket.on('sendMessage', (content) => {
        console.log(`${name} send a message : ${content}`);
        const message = {
            time: Date.now(),
            sender: name,
            content: content,
        };
        history.push(message);

        // 通知所有客户端更新聊天列表
        socket.broadcast.emit('receieveMessage', message);
    });

    //客户端断开连接
    socket.on('disconnect', (reason) => {
        console.log(`${name} disconnect , reason ${reason}`);
        users.delete(name);

        // 通知所有客户端更新聊天列表
        socket.broadcast.emit('online', [...users.keys()]);

        // 接受服务器发来的消息
        socket.on('online', (userList) => {
            socket.emit('online', [...users.keys()]);
            console.log(`online:${userList}`);
        });

    });


    // 增加中间件，获取所有历史记录
    app.use((ctx) => {
        if (ctx.request.path === '/history') {
            ctx.body = history;
        }
    });
});







server.listen(port, hostname, () => {
    console.log(`server running at http://${hostname}:${port}`);
})